package org.cqust.backend.controller.base;

import org.cqust.backend.entity.User;
import org.springframework.security.core.context.SecurityContextHolder;

public class BaseController {
    /**
     * 获取当前登录用户
     * @return 用户信息
     */
    protected static User getUser(){
        var authentication = SecurityContextHolder.getContext().getAuthentication();
        return (User)authentication.getPrincipal();
    }

    /**
     * 获取当前登录用户的ID
     * @return 用户ID
     */
    protected static long getUserId(){
        var authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User)authentication.getPrincipal();
        return getUser().getId();
    }

    /**
     * 检查用户是否具有某个权限
     */
    protected static boolean hasAuthority(String authority){
        var authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals(authority));
    }
}
